#include "StdAfx.h"
#include "ApproachDrawerHolder.h"
#include "ZeroInit.h"
#include "AutoCriticalSection.h"

CApproachDrawerHolder::CApproachDrawerHolder(void)
{
	m_gridParam = zero_init<CGridParam>();
}

CApproachDrawerHolder::~CApproachDrawerHolder(void)
{
}


void CApproachDrawerHolder::Draw(CDC *pCdc, int nWidth, int nHeight) const
{
	CAutoCriticalSection acs(m_csList);

	CApproachDrawer::ListPtr::const_iterator it = m_listPtrAppr.begin();
	CApproachDrawer::ListPtr::const_iterator end = m_listPtrAppr.end();
	for (; it!=end; ++it)
	{
		const CApproachDrawer::Ptr pApp = *it;
		pApp->Draw(pCdc, nWidth, nHeight);
	}
}

void CApproachDrawerHolder::Clean()
{
	CAutoCriticalSection acs(m_csList);
	m_listPtrAppr.clear();
}

void CApproachDrawerHolder::Load(ListPtrApproachs &ListApprchs, const CGridParam &gridParam)
{
	CAutoCriticalSection acs(m_csList);

	m_gridParam = gridParam;
	ListPtrApproachs::iterator it = ListApprchs.begin();
	ListPtrApproachs::iterator end = ListApprchs.end();
	for (; it!=end; ++it)
	{
		CApproachDrawer::Ptr app(new CApproachDrawer(*it, m_gridParam));
		m_listPtrAppr.push_back(app);
	}
}

bool CApproachDrawerHolder::Append(CApproach::Ptr pApproach)
{
	if(!pApproach)
		return false;
	if(!m_gridParam.IsIncludedRange(pApproach->m_pAsteroidOrbitParam->GetVariousParam()))
		return false;
	if(!m_gridParam.IsIncludedTime(pApproach->m_dTime))
		return false;

	CAutoCriticalSection acs(m_csList);
	CApproachDrawer::Ptr app(new CApproachDrawer(pApproach, m_gridParam));
	m_listPtrAppr.push_back(app);
	return true;
}

const CApproachDrawer::Ptr CApproachDrawerHolder::GetNearest(double dx, double dy, double *dDist) const
{
	CApproachDrawer::Ptr resApp;
	double dMindist = -1;

	CAutoCriticalSection acs(m_csList);

	CApproachDrawer::ListPtr::const_iterator it = m_listPtrAppr.begin();
	CApproachDrawer::ListPtr::const_iterator end = m_listPtrAppr.end();
	for (; it!=end; ++it)
	{
		double dDist = (*it)->GetDistance(dx, dy);
		if(dMindist < 0.0 || dDist < dMindist)
		{
			dMindist = dDist;
			resApp = (*it);
		}
	}
	if(dDist)
		*dDist = dMindist;
	return resApp;
}
